package demo.springcloud.webflux.gateway.filter;

import demo.springcloud.webflux.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalGatewayFilter implements GlobalFilter,Ordered {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token;
        HttpHeaders headers = exchange.getRequest().getHeaders();
        if (headers.containsKey("Authorization") && headers.get("Authorization").get(0).contains("Bearer")) {
            token = headers.get("Authorization").get(0).substring(7, headers.get("Authorization").get(0).length());
            System.out.println("token: " + token);
            Claims claims = jwtUtil.parseJWT(token);
            if(claims!=null){
                String userId = claims.getId();
                exchange.getAttributes().put("userId", userId);
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
